import { View, Button, Input, Textarea,Text, RichText ,Image} from '@tarojs/components'
import {  ActionSheet } from '@antmjs/vantui'
import React, { Suspense, useEffect, useState } from 'react'
import type { ActionSheetItem } from '@antmjs/vantui'


import arrowRightIcon from '@/assets/images/arrow-right.png'

import useInitAction from "@/hooks/useInitAction";

import { handleCommonUpload, handleInitStoreBaseInfo, toPage, showToast, handleLoginCallback, handleCompressImg, generateRegionData } from '@/common/util'
import Taro, { useDidShow } from '@tarojs/taro'
import { DEFAULT_AVATAR, PAGE_TYPE, RESPONSE_CODE, STORE_KEY } from '@/common/config'
import { API_URL } from '@/common/serviveApi'
// import useProfileInfoAction from '@/hooks/useProfileInfoAction'

import useSeviceTypeAction from '@/hooks/useSeviceTypeAction'
import useJobTypeAction from '@/hooks/useJobTypeAction'
// import useRegionAction from "@/hooks/useRegionAction";
import { useStore } from '@/store';
import { observer } from 'mobx-react-lite';

import './userJoinInfo.scss'
import { DataItem, IRegionResponse, IResponseSuccess } from '@/typing'
import { handleRegionList } from '@/common/service'

const JobDialog = React.lazy(() => import('@/components/jobDialog/jobDialog'));
const CascaderActionSheet = React.lazy(() => import('@/components/cascaderActionSheet/cascaderActionSheet'));
const AddSerivceDialog = React.lazy(() => import('@/components/addSerivceDialog/addSerivceDialog'));



const UserJoinInfo: React.FC = () => {
    // const { handleInitRegionList } = useRegionAction()
      const { serviceStore,jobStore} = useStore()

   
    const { setServiceTypeList, handleInitServiceTypeDescT ,handleInitServiceTypeList,serviceTypeList} = useSeviceTypeAction()
    const { handleInitJobDescT, setChannelCategoriesList ,handleInitJobListT,channelCategoriesList} = useJobTypeAction();

    const [regionData, setRegionData] = useState<DataItem[]>()
    const [codeToText, setCodeToText] = useState<{ [key: string]: string }>({})
    // 获取屏幕高度
    const { bottomSafeHeight } = useInitAction()
    // 性别选择框显示状态
    const [sexSelectShow, setSexSelectShow] = useState(false)
    // 页面显示状态
    const [pageShow, setPageShow] = useState(false)

    // 性别
    const [sex, setSex] = useState('')
    // 地区选择框显示状态
    const [areaVisible, setAreaVisible] = useState(false)
    // 用户头像
    const [avatar, setUserAvatar] = useState('')

    // 地区
    const [area, setArea] = useState('')

    // 昵称
    const [nickname, setNickname] = useState('');
    // 个人简介
    const [introduction, setIntroduction] = useState('')
    // 用户自述
    const [userReadMe, setUserReadMe] = useState('')
    // 职业描述
    const [jobDesc, setJobDesc] = useState('');
    // 职业选择框显示状态
    const [jobSelectShow, setJobSelectShow] = useState(false)

    const [userService, setUserService] = useState('')

    const [serivceDialogShow, setSerivceDialogShow] = useState(false)

    const [actions] = useState<ActionSheetItem[]>([
        {
            name: '男',
        },
        {
            name: '女 ',
        },
    ])

    const handleSelectSex = (e) => {
        setSex(e.detail.name)
        const storeBaseUserInfo = handleInitStoreBaseInfo();
        const computedGender = e.detail.name === '男' ? 1 : 2
        storeBaseUserInfo['gender'] = computedGender
        Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))
        Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))
    }
    const handleNicknameInput = (e) => {

        setNickname(e.detail.value)
        const storeBaseUserInfo = handleInitStoreBaseInfo();
        storeBaseUserInfo['nickname'] = e.detail.value
        Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))

    }
    const handleUserDescriptionInput = (e) => {
        setIntroduction(e.detail.value)
        const storeBaseUserInfo = handleInitStoreBaseInfo();
        storeBaseUserInfo['introduction'] = e.detail.value
        Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))
    }
    const handleOnChooseAvatar = async (e) => {


        const { avatarUrl } = e.detail
         handleCompressImg([{url:avatarUrl}],80).then(async(compressedPath)=>{
            const thumb = String(compressedPath)
            let uploadAvatarUrlRes = await handleCommonUpload(thumb);
        if (uploadAvatarUrlRes.code === RESPONSE_CODE.LOGIN_EXPIRE || uploadAvatarUrlRes.code === RESPONSE_CODE.LOGIN_NEED) {
            // Taro.removeStorageSync(STORE_KEY.PHONE)
            handleLoginCallback(async () => {
                uploadAvatarUrlRes = await handleCommonUpload(thumb);
            })
           
        } else if (uploadAvatarUrlRes.code === RESPONSE_CODE.SUCCESS) {
            const storeBaseUserInfo = handleInitStoreBaseInfo();
            storeBaseUserInfo['avatar'] = uploadAvatarUrlRes.fileUrl
            Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))

            setUserAvatar(uploadAvatarUrlRes.fileUrl)
        }
         })
       
        


    }
    const handleSetArea = (areaDetail, areaCodeObj) => {

        setArea(areaDetail)
        const storeBaseUserInfo = handleInitStoreBaseInfo();
        storeBaseUserInfo['province_code'] = Number(areaCodeObj['province_code'])
        storeBaseUserInfo['city_code'] = Number(areaCodeObj['city_code'])
        if (areaCodeObj['district_code']) {
            storeBaseUserInfo['district_code'] = Number(areaCodeObj['district_code'])

        } else {
            storeBaseUserInfo['district_code'] = ''
        }


        Taro.setStorageSync(STORE_KEY.BASE_USER_INFO, JSON.stringify(storeBaseUserInfo))


    }
    const handleNextStep = () => {
        const storeJobList = JSON.parse(Taro.getStorageSync(STORE_KEY.JOB_ID_LIST) || '[]')
        const storeServiceTypeList = JSON.parse(Taro.getStorageSync(STORE_KEY.ADD_SERVICE_TYPE) || '[]')

        if (avatar == '') {
            showToast('请设置头像')


            return
        }
        if (nickname == '') {
            showToast('请输入昵称')
            return
        }
        if (sex == '') {
            showToast('请选择性别')


            return
        }
        if (storeJobList.length === 0) {
            showToast('请至少选择一个职业')

            return
        }
        if (area == '') {
            showToast('请选择地区')


            return
        }
        if (introduction == '') {
            showToast('请输入个人简介')

            return
        }
        if (storeServiceTypeList.length === 0) {
            showToast('请至少选择一个服务')

            return
        }

        toPage(PAGE_TYPE.TOPIC_SETTING)

    }
    const handleGoReadMe = () => {
        toPage(PAGE_TYPE.USER_README)
    }
    const handleInit =async () => {
        const regionRes = await handleRegionList() as IResponseSuccess<IRegionResponse>
        if (regionRes.statusCode === RESPONSE_CODE.AJAX_SUCCESS && regionRes.data.code === RESPONSE_CODE.SUCCESS) {
            const regionDataList = regionRes.data.data;
            // console.log(regionDataList)
            if (regionDataList && regionDataList.length > 0) {
                const { regionDataT, codeToTextT } = generateRegionData(regionDataList)
                setCodeToText(codeToTextT)
                setRegionData(regionDataT)
                const storeBaseUserInfo = handleInitStoreBaseInfo()
                handleInitJobListT()
                handleInitServiceTypeList()
                if (storeBaseUserInfo) {
                    const baseUserInfo =storeBaseUserInfo
                    if (baseUserInfo.avatar) {
                        const userAvatar = `${baseUserInfo.avatar}`
                        // console.log(userAvatar)
                        setUserAvatar(userAvatar)
                    }
                    if (baseUserInfo.nickname) {
                        setNickname(baseUserInfo.nickname)
                    }
                    if (baseUserInfo.gender) {
                        const sex = baseUserInfo.gender == 1 ? '男' : '女'
                        setSex(sex)
                    } else {
                        setSex('')
                    }
        
        
                    if (baseUserInfo.province_code) {
        
                        const area = baseUserInfo['district_code'] ? `${codeToTextT[baseUserInfo['province_code']]}/${codeToTextT[baseUserInfo['city_code']]}/${codeToTextT[baseUserInfo['district_code']]}` : `${codeToTextT[baseUserInfo['province_code']]}/${codeToTextT[baseUserInfo['city_code']]}`
                        setArea(area)
                    }
                    if (baseUserInfo.introduction) {
                        setIntroduction(baseUserInfo.introduction)
                    }
                    //
                   
                    setPageShow(true)
        
                }

            }



        }
       

    }


    const handleInitJobDesc = () => {
        const storeJobDescList = JSON.parse(Taro.getStorageSync(STORE_KEY.JOB_ID_DESC) || '[]')
      
console.log(Taro.getStorageSync(STORE_KEY.JOB_ID_DESC))
        if (storeJobDescList.length > 0) {

            const storeJobDesc = storeJobDescList.join('、')
            setJobDesc(storeJobDesc)
        }
    }
    const handleInitServiceTypeDesc = () => {
        const storeServiceTypeDescList = JSON.parse(Taro.getStorageSync(STORE_KEY.ADD_SERVICE_TYPE_DESC) || '[]')
   
        console.log(Taro.getStorageSync(STORE_KEY.ADD_SERVICE_TYPE_DESC))

        if (storeServiceTypeDescList.length > 0) {

            const selectedTypeNames = storeServiceTypeDescList.join('、')
            setUserService(selectedTypeNames)
        }
    }
    const handleConfirmAction = (jobIdList) => {

        const storeJobDesc = handleInitJobDescT(jobIdList)
        setJobDesc(storeJobDesc)
        setJobSelectShow(false)

    }
    const handleConfirmServiceAction = (serviceIdList) => {
        if (serviceIdList.length > 0) {

            const storeTypeDesc = handleInitServiceTypeDescT(serviceIdList)
            setSerivceDialogShow(false)
            setUserService(storeTypeDesc)
        } else {
            Taro.showToast({
                title: '请选择服务类型',
                icon: 'none'
            })
        }
    }
    const handlePopStatusAction = (popStatus) => {
        setJobSelectShow(popStatus)

        handleInitJobDesc()
    }
    const handlePopServiceAction = (popStatus) => {
        setSerivceDialogShow(popStatus)

        handleInitServiceTypeDesc()
    }
    useDidShow(() => {
        const userReadMe = Taro.getStorageSync(STORE_KEY.README);
        setUserReadMe(userReadMe);
        handleInitJobDesc()
        handleInitServiceTypeDesc();
    })
   
    const handleInitJobList = async () => {
        const list = jobStore.channelCategoriesList
        setServiceTypeList(serviceStore.serviceTypeList)
        setChannelCategoriesList(list)
    }
    // useEffect(() => {
    //     if(areaVisible){
    //         regionStore.handleInitRegionList()
    //     }
    // },[areaVisible])
    useEffect(() => {
        
       
        // handleInitLogin()
       
        handleInit()

        handleInitJobList();
    }, [])
    return (
        <>
            {pageShow && <View className='min-h-100vh bg-#F6F6F6 pt-34px box-border' style={{ paddingBottom: bottomSafeHeight > 0 ? bottomSafeHeight + 'px' : '50rpx' }}>
                {/* <View className="taro_html" dangerouslySetInnerHTML={{ __html: html }}></View> */}
                <View className='w-708px mx-auto bg-#fff pt-54px box-border'>
                    <View className='w-192px mx-auto flex flex-col items-center relative'>
                      <View className='w-192px h-192px rounded-192px overflow-hidden'> 
                        {avatar? <Image src={`${API_URL}${avatar}`} className='w-192px h-192px'></Image> : <Image src={DEFAULT_AVATAR} className='w-192px h-192px'></Image>}
                        
                         </View>
                        <Text className='text-#161618 text-30px font-medium mt-8px'>设置头像</Text>
                        <Button className='user-button  border-0 rounded-0 bg-transparent absolute w-200px h-240px top-0 left-0 px-0' openType='chooseAvatar' onChooseAvatar={handleOnChooseAvatar}></Button>
                        {/* <Text className='mt-36px text-#161618 text-30px font-medium'>设置头像</Text> */}
                    </View>
                    <View className='mt-22px pl-46px pr-56px box-border'>
                        <View className='w-full flex items-center justify-between h-124px'>
                            <View className='text-#161618 text-32px'>昵称</View>
                            <View className='ml-48px flex-1 flex items-center justify-between'>
                                <Input placeholder='请输入' placeholderClass='user-name' value={nickname} onInput={handleNicknameInput} style='font-size:32rpx;width:100%;color:#333' type='nickname' maxlength={15} />
                                {/* <View className='text-#999999 text-32px'>请输入</View> */}
                                {/* <Image src={arrowRightIcon} className='w-17px h-30px mt-4px'></Image> */}
                            </View>

                        </View>
                        <View className='w-full h-2px bg-#E9E9E9'></View>
                        <View className='w-full flex items-center justify-between h-124px' onClick={() => setSexSelectShow(true)}>
                            <View className='text-#161618 text-32px'>性别</View>
                            <View className='ml-48px flex-1 flex items-center justify-between'>
                                <View className='text-32px' style={{ color: sex ? '#333' : '#999' }}>{sex ? sex : '请选择'}</View>
                                <Image src={arrowRightIcon} className='w-17px h-30px mt-4px'></Image>
                            </View>

                        </View>
                        <View className='w-full h-2px bg-#E9E9E9'></View>
                        <View className='w-full flex items-center justify-between h-124px' onClick={() => setJobSelectShow(true)}>
                            <View className='text-#161618 text-32px'>职业</View>
                            <View className='ml-48px flex-1 flex items-center justify-between'>
                                <View className='text-32px flex-1 line-clamp-1' style={{ color: jobDesc ? '#333' : '#999' }}>{jobDesc ? jobDesc : '请选择'}</View>
                                <Image src={arrowRightIcon} className='w-17px h-30px mt-4px'></Image>
                            </View>

                        </View>
                        <View className='w-full h-2px bg-#E9E9E9'></View>
                        <View className='w-full flex items-center justify-between h-124px' onClick={() => setAreaVisible(true)}>
                            <View className='text-#161618 text-32px' >地区</View>
                            <View className='ml-48px flex-1 flex items-center justify-between'>
                                <View className='text-#999999 text-32px' style={{ color: area ? '#333' : '#999' }}>{area ? area : '请选择'}</View>
                                <Image src={arrowRightIcon} className='w-17px h-30px mt-4px'></Image>
                            </View>

                        </View>
                        <View className='w-full h-2px bg-#E9E9E9'></View>
                        <View className='w-full flex items-center justify-between py-36px box-border min-h-124px'>
                            <View className='text-#161618 text-32px'>简介</View>
                            <View className='ml-48px flex-1 flex items-center justify-between'>
                                {/* <View className='text-#999999 text-32px'>一句话自我介绍</View> */}
                                <Textarea placeholder='一句话自我介绍' value={introduction} onInput={handleUserDescriptionInput} style='width:100%;color:#333;font-size:32rpx;box-sizing:border-box;min-height:64rpx;' placeholderClass='user-textarea' autoHeight maxlength={36} />
                                {/* <Image src={arrowRightIcon} className='w-17px h-30px mt-4px'></Image> */}
                            </View>

                        </View>
                        <View className='w-full h-2px bg-#E9E9E9'></View>
                        <View className='w-full flex items-center justify-between py-44px box-border'>
                            <View className='text-#161618 text-32px'>自述</View>
                            <View className='ml-48px flex-1 flex items-center justify-between' onClick={handleGoReadMe}>
                                {
                                    userReadMe ?
                                     <View className='text-32px flex-1 text-#333 taro_html line-clamp-3 '>
                                        <RichText nodes={userReadMe}></RichText>
                                     </View>
                                      :
                                        <View className='text-32px flex-1 text-#999' >选填，可做详细的自我介绍</View>
                                }

                                <Image src={arrowRightIcon} className='w-17px h-30px mt-4px ml-20px'></Image>
                            </View>

                        </View>
                        <View className='w-full h-2px bg-#E9E9E9'></View>
                        <View className='w-full flex items-center justify-between h-124px' onClick={() => setSerivceDialogShow(true)}>
                            <View className='text-#161618 text-32px' >提供服务</View>
                            <View className='ml-48px flex-1 flex items-center justify-between'>
                                <View className='text-#999999 text-32px' style={{ color: userService ? '#333' : '#999' }}>{userService ? userService : '请选择'}</View>
                                <Image src={arrowRightIcon} className='w-17px h-30px mt-4px'></Image>
                            </View>

                        </View>
                    </View>
                </View>
                <View className='w-400px h-108px text-#333333 flex items-center justify-center text-36px mx-auto mt-62px bg-#fff' onClick={handleNextStep}>下一步</View>

                <ActionSheet
                    cancelText='取消'
                    show={sexSelectShow}
                    actions={actions}
                    onClose={() => setSexSelectShow(false)}
                    onCancel={() => setSexSelectShow(false)}
                    onSelect={(e) => handleSelectSex(e)}
                />
                <Suspense>
                    <JobDialog channelCategoriesList={channelCategoriesList} show={jobSelectShow} handlePopStatus={handlePopStatusAction} handleConfirm={handleConfirmAction}></JobDialog>
                </Suspense>

                <Suspense>
                    {regionData && <CascaderActionSheet codeToText={codeToText} regionData={regionData} areaVisible={areaVisible} handleCloseAreaAction={() => setAreaVisible(false)} handleAreaChangeAction={(areaDetail, areaCodeObj) => handleSetArea(areaDetail, areaCodeObj)}></CascaderActionSheet>}

                </Suspense>
                <Suspense>
                    <AddSerivceDialog serviceTypeList={serviceTypeList} show={serivceDialogShow} handlePopStatus={handlePopServiceAction} handleConfirm={handleConfirmServiceAction}></AddSerivceDialog>

                </Suspense>

                {/* <CascaderActionSheet areaVisible={areaVisible} handleCloseAreaAction={() => setAreaVisible(false)} handleAreaChangeAction={(areaDetail, areaCodeObj) => handleSetArea(areaDetail, areaCodeObj)}></CascaderActionSheet> */}

            </View>}
        </>

    )
}

export default observer(UserJoinInfo);